<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/1/5
 * Time: 11:26
 */

namespace app\index\controller;


use app\index\validate\Valid;
use think\Request;
use think\Db;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
class Wdxsdd extends Commonwork
{
    public function index(){
        $zoning = $this->request->get('zoning');
        $this->assign('zoning',$zoning);
        $provice = $this->request->get('provice');
        $this->assign('provice',$provice);
        $city = $this->request->get('city');
        $this->assign('city',$city);
        $ordersn = $this->request->get('ordersn');
        $this->assign('ordersn',$ordersn);
        $jxssn = $this->request->get('jxssn');
        $this->assign('jxssn',$jxssn);
        $jxsname = $this->request->get('jxsname');
        $this->assign('jxsname',$jxsname);
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);
        $minNum = $this->request->get('minNum');
        $this->assign('minNum',$minNum);
        $maxNum = $this->request->get('maxNum');
        $this->assign('maxNum',$maxNum);
        $applyStatus = $this->request->get('applyStatus');
        $this->assign('applyStatus',$applyStatus);

        $where = [];
        $where['sqr'] = session('employee_id');
        $cus_ids = [];
        if($zoning){
            $cus_ids = db('cg_market_zoning')->where('title','like',"%{$zoning}%")->column('id');
        }
        if($provice){
            $provice_ids = db('cg_market_provice')->where('title','like',"%{$provice}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$provice_ids):$provice_ids;
        }
        if($city){
            $city_ids = db('cg_market_city')->where('title','like',"%{$city}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$city_ids):$city_ids;
        }
        if($ordersn){
            $where['sn'] = ['like',"%{$ordersn}%"];
        }
        if($jxssn){
            $jxsids = db('cg_jxs')->where('sn','like',"%{$jxssn}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($jxsname){
            $jxsids = db('cg_jxs')->where('title','like',"%{$jxsname}%")->column('id');
            $cus_ids = $jxsids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($start&&$end){
            $where['jyfhrq'] = [['>',$start],['<',$end],'and'];
        }elseif($start){
            $where['jyfhrq'] = ['>',$start];
        }elseif($end){
            $where['jyfhrq'] = ['<',$end];
        }
        if($minNum&&$maxNum){
            $where['yszje'] = [['>',$minNum],['<',$maxNum],'and'];
        }elseif($minNum){
            $where['yszje'] = ['>',$minNum];
        }elseif($maxNum){
            $where['yszje'] = ['<',$maxNum];
        }
        if($applyStatus){
            $where['status'] = $applyStatus;
        }
        $cus_ids = array_unique($cus_ids);
        if($cus_ids){
            $where['cusName'] = ['in',$cus_ids];
        }
        $count = db('cg_order')->where($where)->count();
        $data = db('cg_order')->where($where)->order('id desc')->paginate(10,$count);
//        echo db('cg_order')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $t = $v['cusName'];
            $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$t)->value('t.title');
            $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$t)->value('t.title');
            $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$t)->value('t.title');
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v['jxssn'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
            $v['jxsname'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');
            $v["statustype"]=db("cg_ti_hexiao_status")->where(["id"=>$v["status"]])->value("title");
            if($v["yhPolicy"]){
                $psn=db("cg_channel_preferential_policy_cxfa pf")->join("cg_channel_preferential_policy p","pf.p_id=p.id")->where(["pf.id"=>$v["yhPolicy"]])
                ->field("p.sn,pf.p_id")->find();
                $pno=db("cg_channel_preferential_policy_cxfa")->where("p_id={$psn["p_id"]} and id<={$v["yhPolicy"]}")->count();
                $v["yhPolicy"]=$psn["sn"].'-'.$pno;
            }else{
                $v["yhPolicy"]="-";
            }
            

            $data[$k] = $v;
        }
        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('maxpage',$maxpage);
        return $this->fetch();
    }

    public function add($from=1){
        $this->assign("from",$from);
        if($_POST){
            echo json_encode(['success'=>false,'msg'=>'请添加销售订单明细']);die;
        }
        $sqr = db('employee')->where('id',session('employee_id'))->value('em_name');
        $this->assign('sqr',$sqr);
        $sqrbm = db('department t')->join('department_employee t2','t2.department_id=t.id')->where(['t2.employee_id'=>session('employee_id'),'t2.index'=>1])->value('t.de_name');
        $this->assign('sqrbm',$sqrbm);
        $isnet=db("system_param")->where("k='dingDanIsWangDian'")->value('v');
        $this->assign("isnet",$isnet);
        //echo $isnet;
        $isbuhuo=db("system_param")->where("k='isTianJiaBuHuo'")->value('v');
        $this->assign("isbuhuo",$isbuhuo);
        $isbufei=db("system_param")->where("k='isTianJiaBuFei'")->value('v');
        $this->assign("isbufei",$isbufei);
        return $this->fetch('form');
    }

    public function updateAttach($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = db('cg_order')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');
        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            db('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        //记录日志-备份原记录
//        $old = $this->log_start($id);
        db('cg_order')->where(array('id'=>$id))->update($data);
        //记录日志-开始记录
//        $this->log_end($id,$old);
        //新增附件\更新附件表
        if(isset($attachids)){

            db('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_net'));
        }

    }

    /**
     * 详情
     */
    public function view(){
        $id = $this->request->param('id');
        $data =  db('cg_order')->where('id',$id)->find();
        $data['list'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>['in',[1,2]]])->select();
        $data['sqr'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['sqrbm'] = db('job t')->join('job_employee t2','t.id=t2.job_id')->where('t2.employee_id',$data['sqr'])->value('job_name');
        $data['sqrq'] = date('Y-m-d',$data['sqrq']);
        $data['cksqd_id'] = db('cg_cksqd')->where('order_id',$id)->value('id');
        $data['cksqd_sn'] = db('cg_cksqd')->where('order_id',$id)->value('sn');
        if($data['cusType']==1){
            $data['cusName'] = db('cg_jxs')->where('id',$data['cusName'])->value('title');
            $data['cusSN'] = db('cg_jxs')->where('id',$data['cusName'])->value('sn');
        }else{
            $data['cusName'] = db('cg_net')->where('id',$data['cusName'])->value('title');
            $data['cusSN'] = db('cg_net')->where('id',$data['cusName'])->value('sn');
        }
        foreach($data['list'] as $k=>$v){
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['mxbh'] = $data['sn'].'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            //$v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            /*$zj1 += $v['num'];
            $zj2 += $v['dzsl'];
            $zj3 += $v['yje'];
            $zj4 += $v['ysje'];*/
            if($v['dyddmxid'])
                $v['dyddmxid'] = $data['sn'].'-'.db('cg_order_list')->where('id',$v['dyddmxid'])->value('sn');

            $data['list'][$k]= $v;
        }
        $data['huobu'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->select();
        foreach($data['huobu'] as $k=>$v){
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['prod_sn'] = db('pro_products')->where('id',$v['product'])->value('pro_no');
            $main_sn = db('cg_ti_hexiao_list t')->join('cg_ti_hexiao t2','t2.id=t.hx_id')->where('t.id',$v['hxdmxbh'])->value('t2.sn');
            $sub_sn = db('cg_ti_hexiao_list')->where('id',$v['hxdmxbh'])->value('sn');
            $v['hxdbh'] = $main_sn.'_'.$sub_sn;
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            $v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $data['huobu'][$k] = $v;
        }
        $data['bufei'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->select();
        $this->assign('data',$data);
         $logs=$this->getlog(23,$id);
            //print_r($logs);
            $this->assign("logs",$logs);
        echo $this->fetch();
    }

    //查看流程图
    public function cklct(){
        $id = $this->request->param('id');
        $workId = db('cg_workflow')->where(['ywlx'=>23,'yw_id'=>$id])->value('workId');
        $trackId = db('cg_workflow')->where(['ywlx'=>23,'yw_id'=>$id])->value('trackId');
        header('location:http://61.129.51.183:10010/hzwf73/workflow/module/workflow/flowchart.jsp?workId='.$workId.
            '&trackId='.$trackId);
    }


    /**
     * 修改
     * @return mixed
     */
    public function update($from=1){
        $this->assign("from",$from);
        $id = $this->request->param('id');
        $this->assign('id',$id);
        if($_POST){
            $data = Request::instance()->post();
            //echo json_encode(['success'=>false,'msg'=>$data["status"]]);exit;
            $savet=$data["savet"];
            unset($data["savet"]);
            $valid = new Valid([
                'cusType|客户类型'=>'require',
                'cusName|客户名称'=>'require',
                'shdz|收货地址'=>'require',
                'shr|收货人'=>'require',
                'dh|收货电话'=>'require',
                'jyfhrq|建议发货日期'=>'require|dateFormat:Y-m-d',
                'zysx|注意事项'=>'require',
            ]);
            if(false==$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
            $od=db("cg_order_list")->where(["order_id"=>$data["id"]])->count();
            if(!$od){
                echo json_encode(['success'=>false,'msg'=>"至少添加一条明细"]);die;
            }
            if($data['cusType']==1){
                $data['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t.id=t2.zoning')->where('t2.id',$data['cusName'])->value('t.title');
                $data['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t.id=t2.provice')->where('t2.id',$data['cusName'])->value('t.title');
                $data['city'] = db('cg_market_city t')->join('cg_jxs t2','t.id=t2.city')->where('t2.id',$data['cusName'])->value('t.title');
                $data['khbh'] = db('cg_jxs')->where('id',$data['cusName'])->value('sn');
                $data['khmc'] = db('cg_jxs')->where('id',$data['cusName'])->value('title');
            }else{
                $data['zoning'] = db('cg_market_zoning t')->join('cg_net t2','t.id=t2.zoning')->where('t2.id',$data['cusName'])->value('t.title');
                $data['provice'] = db('cg_market_provice t')->join('cg_net t2','t.id=t2.provice')->where('t2.id',$data['cusName'])->value('t.title');
                $data['city'] = db('cg_market_city t')->join('cg_net t2','t.id=t2.city')->where('t2.id',$data['cusName'])->value('t.title');
                $data['khbh'] = db('cg_net')->where('id',$data['cusName'])->value('sn');
                $data['khmc'] = db('cg_net')->where('id',$data['cusName'])->value('title');
            }
            $data['yhPolicymc'] = db('cg_channel_preferential_policy')->where('id',$data['yhPolicy'])->value('title');
//            $data['jyfhrq'] = strtotime($data['jyfhrq']);
            $data['ctime'] = time();
            $data['cuser'] = session('employee_id');
            unset($data['attach']);
            unset($data['remove']);
            $bool = db('cg_order')->update($data);
            if($savet==3){
                $jieguo=$this->gowork(23,$data["id"]);
            }
            if(false!==$bool){
                $this->updateAttach($id);
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
        $data = db('cg_order')->where('id',$id)->find();
        if($data["status"]==2){
            $btn=$this->getbton(23,$id);
            $this->assign("btn",$btn);
            $logs=$this->getlog(23,$id);
                    //print_r($logs);
            $this->assign("logs",$logs);
        }
        $data['sqr_name'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['sqrbm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where(['t2.employee_id'=>session('employee_id'),'t2.index'=>1])->value('t.de_name');

        if($data['cusType']==1)
            $data['cusName_name'] = db('cg_jxs')->where('id',$data['cusName'])->value('title');
        else
            $data['cusName_name'] = db('cg_net')->where('id',$data['cusName'])->value('title');

        $data['status_name'] = $this->status($data['status']);
        $yhtitle=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$data['yhPolicy'])->value('p.title');
        if($data["yhPolicy"]){
            $yhpid=db("cg_channel_preferential_policy_cxfa")->where("id={$data['yhPolicy']}")->value("p_id");
            $yhnum=db("cg_channel_preferential_policy_cxfa")->where("id<={$data['yhPolicy']} and p_id=$yhpid")->count();
            $data['yhPolicyName'] = $yhtitle."-促销方案".$yhnum;
        }
        
        $zj1 = 0;
        $zj2 = 0;
        $zj3 = 0;
        $zj4 = 0;

        //查询销售订单明细
        $list = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>['in',[1,2]]])->select();
        foreach($list as $k=>$v){
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            //$v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj1 += $v['num'];
            $zj2 += $v['dzsl'];
            $zj3 += $v['yje'];
            $zj4 += $v['ysje'];
            if($v['dyddmxid'])
                $v['dyddmxid'] = $data['sn'].'-'.db('cg_order_list')->where('id',$v['dyddmxid'])->value('sn');
            $list[$k] = $v;
        }
        $data['list'] = $list;

        //查询货补订单明细
        $list = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->select();
        foreach($list as $k=>$v){
//            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
//            $v['prod_sn'] = db('pro_products')->where('id',$v['product'])->value('pro_no');
            $main_sn = db('cg_ti_hexiao_list t')->join('cg_ti_hexiao t2','t2.id=t.hx_id')->where('t.id',$v['hxdmxbh'])->value('t2.sn');
            $sub_sn = db('cg_ti_hexiao_list')->where('id',$v['hxdmxbh'])->value('sn');
            $v['hxdbh'] = $main_sn.'_'.$sub_sn;
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            $v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $zj2 += $v['num'];
            $zj3 += $v['ysje'];
            $zj4 += $v['ysje'];
            $list[$k] = $v;
        }
        $data['huobu'] = $list;

        //查询补费订单明细
        $list2 = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->select();
        $xj = 0;
        foreach($list2 as $k=>$v){
            $v['hxdbh'] = db('cg_ti_hexiao')->where('id',$v['hxdmxbh'])->value('sn');
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $list2[$k] = $v;
            $xj += $v['bfje'];
        }
        $data['bufei'] = $list2;

        
        $this->assign('xj',$xj);
        $zj1 = round($zj1,4);
        $zj2 = round($zj2,4);
        $zj3 = round($zj3,4);
        $zj4 = round($zj4,4);
        $this->assign([
            'zj1'=>$zj1,
            'zj2'=>$zj2,
            'zj3'=>$zj3,
            'zj4'=>$zj4,
        ]);
       /* $ddyszje= $zj4-$xj;
        $this->assign('ddyszje',$ddyszje);*/

        //查询是否有渠道优惠政策
        if($data['cusType']==1){
            $jxs_id=$data['cusName'];
            $data["jxs"]=$data['cusType'];
        }else{
            $net=db("cg_net")->where(["id"=>$data['cusType']])->find();
            $jxs_id=db("cg_system")->where(["id"=>$net["system_id"]])->value("jxs");
            $data["jxs"]=$jxs_id;
        }
        $city = db('cg_jxs')->where('id',$jxs_id)->value('city');
        $provice = db('cg_jxs')->where('id',$jxs_id)->value('provice');
        $zoning = db('cg_jxs')->where('id',$jxs_id)->value('zoning');
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id,t.title,t.sn')->group("t.id")
            ->count();
//        echo db('cg_ti')->getLastSql();
        $this->assign('qdyhzc',$qdyhzc);
        $this->assign('data',$data);
        $isnet=db("system_param")->where("k='dingDanIsWangDian'")->value('v');
        $this->assign("isnet",$isnet);
        $isbuhuo=db("system_param")->where("k='isTianJiaBuHuo'")->value('v');
        $this->assign("isbuhuo",$isbuhuo);
        $isbufei=db("system_param")->where("k='isTianJiaBuFei'")->value('v');
        $this->assign("isbufei",$isbufei);
        return $this->fetch('form');
    }

    //优惠政策
    public function yhPolicy(){
        $jxs_id = $this->request->param('jxs_id');
        $city = db('cg_jxs')->where('id',$jxs_id)->value('city');
        $provice = db('cg_jxs')->where('id',$jxs_id)->value('provice');
        $zoning = db('cg_jxs')->where('id',$jxs_id)->value('zoning');
        //查询是否有渠道优惠政策
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id,t.title,t.sn')->group("t.id")
            ->select();
        $data=[];
        foreach ($qdyhzc as $k => $v) {
            # code...
            $mingxi=db("cg_channel_preferential_policy_cxfa")->where("((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and start<='{$time}' and end>='{$time}' and p_id={$v["id"]}")->select();

            foreach ($mingxi as $km => $vm) {
                # code...
                $deid=db("cg_channel_preferential_policy_cxfa")->where("p_id={$v["id"]} and id<={$vm["id"]}")->count();
                $tmp["id"]=$vm["id"];
                $tmp["title"]=$v["title"].'-促销方案'.$deid;
                $data[]=$tmp;

            }
        }
      /*  $qdyhzc = Db::query("select * from(select t2.id,estiGiftCost,t2.title 
 from cg_channel_preferential_policy_cxfa t 
 join cg_channel_preferential_policy t2 on t.p_id=t2.id 
 where start <= '".$time."' and end >= '".$time."' and ((area = 4 and area_id like '%\"{$jxs_id}\"%') or (area = 1 and area_id like '%\"{$zoning}\"%') or (area = 2 and area_id like '%\"{$provice}\"%') or (area = 3 and area_id like '%\"{$city}\"%'))) t group by id");*/
        echo json_encode(['value'=>$data]);
    }

    public function deDetail(){
        $id = $this->request->param('id');

        $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
        $bool = db('cg_order_list')->where('id',$id)->delete();

        $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
        $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
        $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
        $yszje = floatval($yszje)-floatval($qdyhje)-floatval($bfzje);
        $yszje = round($yszje,2);
        db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

        if(false !== $bool){
            echo json_encode(['success'=>true,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'false']);die;
        }
    }
    public function deHuobu(){
        $id = $this->request->param('id');

        $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
        $bool = db('cg_order_list')->where('id',$id)->delete();

        $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
        $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
        $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
        $yszje = $yszje-$qdyhje-$bfzje;
        $yszje = round($yszje,2);
        db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);


        if(false !== $bool){
            echo json_encode(['success'=>true,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'false']);die;
        }
    }
    public function deBufei(){
        $id = $this->request->param('id');

        $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
        $bool = db('cg_order_list')->where('id',$id)->delete();

        $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
        $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
        $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
        $yszje = $yszje-$qdyhje-$bfzje;
        $yszje = round($yszje,2);
        db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

        if(false !== $bool){
            echo json_encode(['success'=>true,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'false']);die;
        }
    }
    //修改明细
    public function upDetail(){
        $id = $this->request->param('id');
        if($_POST){
            $data = Request::instance()->post();

            if(isset($data['num'])){
                $valid = new Valid([
                    'kind|类型'=>'require',
                    'product|订货产品'=>'require',
                    'num|订货数量'=>'require|number',
                    'xgj|订货产品现供价'=>['require','jine'],
                    'xsry|销售人员'=>'require',
                ]);
            }else{
                $valid = new Valid([
                    'kind|类型'=>'require',
                    'product|搭赠产品'=>'require',
                    'dzsl|搭赠数量'=>'require|number',
                    'xgj|搭赠产品现供价'=>['require','jine'],
                    'xsry|销售人员'=>'require',
                ]);
            }

            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }

            //验证搭赠数量是否超过金额的系统参数%限制
            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            //限制
            $limit = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
            //已经搭赠的金额
            $dzje = db('cg_order_list')->where(['order_id'=>$order_id,'dzsl'=>['>',0],'id'=>['<>',$id],'xslx'=>2])->sum('ysje');
            //已经订购的金额
            $je = db('cg_order_list')->where(['order_id'=>$order_id,'dzsl'=>['exp','is null'],'id'=>['<>',$id],'xslx'=>1])->sum('ysje');
            //货补金额
            $hbje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>3])->sum('ysje');
            //补费金额
            $bfje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            if(isset($data['dzsl'])){ //搭赠
                $dz = $dzje+$hbje+$bfje+$data['ysje'];
                $zje = $dz+$je;
                if($dz/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }else{ //订购
                $dz = $dzje+$hbje+$bfje;
                $zje = $dz+$je+$data['ysje'];
                if($dz/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }

            $data['unit'] = $this->request->param('unit');
            $data['prod_sn'] = $this->request->param('prod_sn');
            $data['prod_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
            $data['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t.brand_name');
            $data['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t2.category_name');
            $data['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t3.series_name');
            $data['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t4.sku_name');
            $data['xsry'] = $this->request->post('xsry');
            $data['ssbm'] = $this->request->post('ssbm');
            $data['beizhu'] = $this->request->post('beizhu');

            $bool = db('cg_order_list')->where('id',$id)->update($data);

            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
            db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'保存成功']);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'保存失败']);die;
            }
            die;
        }
        $data = db('cg_order_list')->where('id',$id)->find();
        $data['product_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
        $data['xsry_name'] = db('employee')->where('id',$data['xsry'])->value('em_name');
        $data['ssbm_name'] = db('department')->where('id',$data['ssbm'])->value('de_name');
        $this->assign('data',$data);
        return $this->fetch();
    }

    //修改货补
    public function upHuobu(){
        $id = $this->request->param('id');
        if($_POST){
            $data  = Request::instance()->post();

            //验证
            if(!$data['hxdmxbh']){
                echo json_encode(['success'=>false,'msg'=>'核销单明细编号不能为空']);die;
            }
            if(!$data['kind']){
                echo json_encode(['success'=>false,'msg'=>'类型不能为空']);die;
            }
            if(!$data['product']){
                echo json_encode(['success'=>false,'msg'=>'请选择产品']);die;
            }
            if(!$data['xsry']){
                echo json_encode(['success'=>false,'msg'=>'销售人员不能为空']);die;
            }
            if(!$data['num']||$data['num']==0){
                echo json_encode(['success'=>false,'msg'=>'产品数量不能为空并且必须大于0']);die;
            }

            $bool = db('cg_order_list')->where('id',$id)->update($data);

            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
            db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'操作成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'操作失败']);
            }            
            die;
        }
        $data = db('cg_order_list')->where('id',$id)->find();
        $data['prod_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
        $data['xsry_name'] = db('employee')->where('id',$data['xsry'])->value('em_name');
        $data['hxdmxbh_sn'] = db('cg_ti_hexiao')->where('id',$data['hxdmxbh'])->value('sn');
        $data['prod_id'] = $data['product'];
        $data['prod_price'] = $data['xgj'];
        $data['prod_jine'] = $data['ysje'];
        $this->assign('data',$data);
        //查询限制
        $xz = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
        $xsddzje = db('cg_order_list')->where('order_id',$id)->sum('ysje');
        $xze = round($xsddzje*$xz/100,2);
        //查询已货补的总额
        $this->assign('xze',$xze);

        $uid = session('employee_id');
        $uname = db('employee')->where('id',$uid)->value('em_name');
        $de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
        $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        $this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);
        return $this->fetch();
    }

    //修改补费
    public function upBufei(){
        $id = $this->request->param('id');
        if($_POST){
            //验证
            $data = Request::instance()->post();
//            dump($data);
            $valid = new Valid([
                'hxdmxbh|核销明细编号'=>'require',
                'bfje|本次补费金额'=>'require',
                'xsry|销售人员'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
            if($data['bfje']>$data['hxje']){
                echo json_encode(['success'=>false,'msg'=>'本次补费金额不能大于需补费的核销金额']);die;
            }
            if($data['bfje']>$data['kbje']){
                echo json_encode(['success'=>false,'msg'=>'本次补费金额不能大于销售订单可补费金额']);die;
            }
            $bool = db('cg_order_list')->where('id',$id)->update($data);

            $order_id = db('cg_order_list')->where('id',$id)->value('order_id');
            $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
            db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'修改成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'修改失败']);die;
            }
            die;
        }
        $uid = session('employee_id');
        $uname = db('employee')->where('id',$uid)->value('em_name');
        $de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
        $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        $this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);

        $data = db('cg_order_list')->where('id',$id)->find();
        $data['hxdmxbh_sn'] = db('cg_ti_hexiao')->where('id',$data['hxdmxbh'])->value('sn');
        $data['xsry_name'] = db('employee')->where('id',$data['xsry'])->value('em_name');
        $data['ssbm_name'] = db('department')->where('id',$data['ssbm'])->value('de_name');
        //销售订单可补费金额（元）
        $dhzje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>1])->sum('ysje');//订货总金额
        $bhje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>3])->sum('ysje');//补货总金额
        $bfje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>4])->sum('bfje');//补费总金额
        //系统设置比例
        $bili = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
        $dhzje = $dhzje*($bili/100);
        $kbje  = $dhzje-$bhje-$bfje;
        $this->assign('kbje',$kbje);
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function status($status){
        $d = [
            '1'=>'草稿',
            '2'=>'打回'
        ];
        return $d[$status];
    }

    /**添加销售订单明细
     * @return mixed
     */
    public function add_Dd_detail(){
        if($_POST){
            $data = [];
            $data['kind'] = $this->request->post('kind');
            $data['product'] = $this->request->post('product');
            $data['num'] = $this->request->post('num');
            $data['unit'] = $this->request->post('unit');
            $data['prod_sn'] = $this->request->post('prod_sn');
            $data['ygj'] = $this->request->post('ygj');
            $data['xgj'] = $this->request->post('xgj');
            $data['yje'] = $this->request->post('yje');
            $data['ysje'] = $this->request->post('ysje');
            $dzcp = $this->request->post('dzcp');
            $dzsl = $this->request->post('dzsl');
            $dz_unit = $this->request->post('dz_unit');
            $dz_cpbm = $this->request->post('dz_cpbm');
            $dz_ygj = $this->request->post('dz_ygj');
            $dz_xgj = $this->request->post('dz_xgj');
            $dz_yje = $this->request->post('dz_yje');
            $dz_ysje = $this->request->post('dz_ysje');
            $data['xsry'] = $this->request->post('xsry');
            $data['ssbm'] = $this->request->post('ssbm');
            $data['beizhu'] = $this->request->post('beizhu');
            $data['order_id'] = $this->request->post('order_id');

            $valid = new Valid([
                'kind|类型'=>'require',
                'product|订货产品'=>'require',
                'num|订货数量'=>'require|number',
                'xgj|订货产品现供价'=>['require','jine'],
                'dz_xgj|搭赠产品现供价'=>['jine'],
                'xsry|销售人员'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }

            //验证搭赠数量是否超过金额的系统参数%限制
            $limit = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
            if(!$data['order_id']&&$dz_ysje/$data['ysje']*100>$limit){
                echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
            }elseif($data['order_id']){
                //搭赠金额
                $dzje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['>',0],'xslx'=>2])->sum('ysje');
                $je = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['exp','is null'],'xslx'=>1])->sum('ysje');
                $hbje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>3])->sum('ysje');
                $bfje = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>4])->sum('bfje');
                $dzze = $dzje+$hbje+$bfje+$dz_ysje;
                $zje = $je+$data['ysje'];
                if($dzze/$zje*100>$limit){
                    echo json_encode(['success'=>false,'msg'=>'搭赠+补货+补费金额不能超过订单销售额的'.$limit.'%']);die;
                }
            }

            if($dz_ysje){ //验证渠道优惠政策
                $yhpolicy = $this->request->post('yhPolicy');
                if($yhpolicy){
                    $estiGiftCost = db('cg_channel_preferential_policy')->where('id',$yhpolicy)->value('estiGiftCost');
                    if($data['order_id'])
                        $dz_ysje2 = db('cg_order_list')->where(['order_id'=>$data['order_id'],'dzsl'=>['>',0]])->value('ysje');
                    else
                        $dz_ysje2 = 0;
                    if(($dz_ysje2+$dz_ysje) > $estiGiftCost){
                        echo json_encode(['success'=>false,'msg'=>'搭赠应收金额不能超过渠道优惠政策预计搭赠产生的费用'.$estiGiftCost.'元']);die;
                    }
                }
            }

            if(!$data['order_id']){

                $d = [];
                $d['sn'] = $this->produceSN();
                $d['sqr'] = session('employee_id');
                $d['sqrmc'] = db('employee')->where('id',session('employee_id'))->value('em_name');
                $d['sqrq'] = time();
                $d['cusType'] = $this->request->post('cusType');
                $d['cusName'] = $this->request->post('cusName');
                if($d['cusType']==1){
                    $d['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t.id=t2.zoning')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t.id=t2.provice')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['city'] = db('cg_market_city t')->join('cg_jxs t2','t.id=t2.city')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['khbh'] = db('cg_jxs')->where('id',$d['cusName'])->value('sn');
                    $d['khmc'] = db('cg_jxs')->where('id',$d['cusName'])->value('title');
                }else{
                    $d['zoning'] = db('cg_market_zoning t')->join('cg_net t2','t.id=t2.zoning')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['provice'] = db('cg_market_provice t')->join('cg_net t2','t.id=t2.provice')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['city'] = db('cg_market_city t')->join('cg_net t2','t.id=t2.city')->where('t2.id',$d['cusName'])->value('t.title');
                    $d['khbh'] = db('cg_net')->where('id',$d['cusName'])->value('sn');
                    $d['khmc'] = db('cg_net')->where('id',$d['cusName'])->value('title');
                }
                $d['fpType'] = $this->request->post('fpType');
                $d['yhPolicy'] = $this->request->post('yhPolicy');
                $d['yhPolicymc'] = db('cg_channel_preferential_policy')->where('id',$d['yhPolicy'])->value('title');
                $d['shdz'] = $this->request->post('shdz');
                $d['shr'] = $this->request->post('shr');
                $d['dh'] = $this->request->post('dh');
                $d['jyfhrq'] = $this->request->post('jyfhrq');
                $d['status'] = 1;
                $d['zysx'] = $this->request->post('zysx');
                $data['order_id'] = db('cg_order')->insertGetId($d);
                $basic = 0;

            }else{

                //验证是否已经存在此明细
                $ishas = db('cg_order_list')->where(['order_id'=>$data['order_id'],'product'=>$data['product'],'dzsl'=>['exp','is null']])->count();
                if($ishas){
                    $pro_name = db('pro_products')->where('id',$data['product'])->value('pro_name');
                    echo json_encode(['success'=>false,'msg'=>'本订单中已经存在名称为：'.$pro_name]);die;
                }

                $basic = db('cg_order_list')->where('order_id',$data['order_id'])->max('sn'); //编号递增开始位置基础

            }
            $data['sn'] = $basic+1;
            if($data['kind']==1){
                $data['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t.brand_name');
                $data['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t2.category_name');
                $data['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t3.series_name');
                $data['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$data['product'])->value('t4.sku_name');
                $data['prod_name'] = db('pro_products')->where('id',$data['product'])->value('pro_name');
            }else{
                $data['prod_name'] = db('pro_materials')->where(['id'=>$data['product'],'m_type'=>2])->value('material_name');
            }
            $data['xslx'] = 1;
            $bool = db('cg_order_list')->insertGetId($data);
            if(false!==$bool){
                if($dzsl>0){
                    $insert = [];
                    $insert['dyddmxid'] = $bool;
                    $insert['kind'] = $data['kind'];
                    $insert['product'] = $dzcp;
                    $insert['dzsl'] = $dzsl;
                    $insert['unit'] = $dz_unit;
                    if($data['kind']==1) {
                        $insert['brand'] = db('pro_brands t')->join('pro_category t2','t.id=t2.brand_id')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t.brand_name');
                        $insert['category'] = db('pro_category t2')->join('pro_series t3','t3.category_id=t2.id')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t2.category_name');
                        $insert['series'] = db('pro_series t3')->join('pro_sku t4','t4.series_id=t3.id')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t3.series_name');
                        $insert['sku'] = db('pro_sku t4')->join('pro_products t5','t5.sku_id=t4.id')->where('t5.id',$dzcp)->value('t4.sku_name');
                        $insert['prod_name'] = db('pro_products')->where('id',$dzcp)->value('pro_name');
                    }else{
                        $data['prod_name'] = db('pro_materials')->where(['id'=>$dzcp,'m_type'=>2])->value('material_name');
                    }
                    $insert['prod_sn'] = $dz_cpbm;

                    $insert['ygj'] = $dz_ygj;
                    $insert['xgj'] = $dz_xgj;
                    $insert['yje'] = $dz_yje;
                    $insert['ysje'] = $dz_ysje;
                    $insert['xsry'] = $this->request->post('xsry');
                    $insert['ssbm'] = $this->request->post('ssbm');
                    $insert['beizhu'] = $this->request->post('beizhu');
                    $insert['order_id'] = $data['order_id'];
                    $insert['sn'] = $basic+2;
                    $insert['xslx'] = 2;
                    db('cg_order_list')->insert($insert);
                }
                $ysje = db('cg_order_list')->where('order_id',$data['order_id'])->sum('ysje');
                $qdyhje = db('cg_order_list')->where('order_id',$data['order_id'])->sum('qdyhje');
                $bf = db('cg_order_list')->where(['order_id'=>$data['order_id'],'xslx'=>4])->sum('ysje');
                $ysje = $ysje-$qdyhje-$bf;
                db('cg_order')->where('id',$data['order_id'])->update(['yszje'=>$ysje]);
                echo json_encode(['success'=>true,'msg'=>'保存成功','id'=>$data['order_id']]);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'保存失败']);die;
            }
            die;
        }

        $uid = session('employee_id');
        $uname = db('employee')->where('id',$uid)->value('em_name');
        $de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
        $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        $this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);

        /*//查询优惠政策搭赠限额
        $yhpolicy = $this->request->param('yhpolicy');
        if($yhpolicy){
            $estiGiftCost = db('cg_channel_preferential_policy')->where('id',$yhpolicy)->value('estiGiftCost');
            $this->assign('estiGiftCost',$estiGiftCost);
        }*/
        return $this->fetch();
    }

    /**
     * 添加补货明细
     * @return mixed
     */
    public function buhuo_detail(){
        //销售订单可补金额(元)
        $id = $this->request->param('id');
        if($_POST){
            $hxdmxbh = $this->request->post('hxdmxbh');
            $hxje = $this->request->post('hxje');
            $kind = $this->request->post('kind');
            $kbje = $this->request->post('kbje');
            $xsry = $this->request->post('xsry');
            $ssbm = $this->request->post('ssbm');
            $order_id = $this->request->post('order_id');
            $beizhu = $this->request->post('beizhu');
            $prod_ids = $this->request->post('prod_id/a');
            $prod_price = $this->request->post('prod_price/a');
            $num = $this->request->post('num/a');
            $prod_jine = $this->request->post('prod_jine/a');

            //验证
            if(!$hxdmxbh){
                echo json_encode(['success'=>false,'msg'=>'核销单明细编号不能为空']);die;
            }
            if(!$kind){
                echo json_encode(['success'=>false,'msg'=>'类型不能为空']);die;
            }
            if(!$prod_ids||count($prod_ids)==0){
                echo json_encode(['success'=>false,'msg'=>'请选择产品']);die;
            }
            if(!$xsry){
                echo json_encode(['success'=>false,'msg'=>'销售人员不能为空']);die;
            }

            $max_sn = db('cg_order_list')->where('order_id',$id)->max('sn');
            $max_sn++;

            $insert = [];
            foreach($prod_ids as $k=>$v){
                if($kind==1){
                    $prod_name = db('pro_products')->where('id',$v)->value('pro_name');
                    $prod_sn =db('pro_products')->where('id',$v)->value('pro_no');
                }else{
                    $prod_name = db('pro_materials')->where('id',$v)->value('material_name');
                    $prod_sn =db('pro_materials')->where('id',$v)->value('material_no');
                }

                $insert[] = [
                    'hxdmxbh'=>$hxdmxbh,
                    'hxje'=>$hxje,
                    'kind'=>$kind,
                    'kbje'=>$kbje,
                    'xsry'=>$xsry,
                    'ssbm'=>$ssbm,
                    'order_id'=>$order_id,
                    'beizhu'=>$beizhu,
                    'product'=>$v,
                    'ygj'=>$prod_price[$k],
                    'xgj'=>$prod_price[$k],
                    'num'=>$num[$k],
                    'ysje'=>$prod_jine[$k],
                    'sn'=>$max_sn,
                    'xslx'=>3,
                    'prod_name'=>$prod_name,
                    'prod_sn'=>$prod_sn,
                    'xsry'=>session('employee_id'),
                    'ssbm'=>db('department_employee')->where('employee_id',session('employee_id'))->value('department_id'),
                ];
                $max_sn++;
                //验证产品数量
                if(!$num[$k]||$num[$k]<=0){
                    echo json_encode(['success'=>false,'msg'=>'产品数量不能为空并且必须大于0']);die;
                }
            }

            $bool = db('cg_order_list')->insertAll($insert);

            $yszje = db('cg_order_list')->where('order_id',$order_id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$order_id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
            db('cg_order')->where('id',$order_id)->update(['yszje'=>$yszje]);

            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'操作成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'操作失败']);
            }
            die;
        }
        //查询限制
        $xz = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
        $xsddzje = db('cg_order_list')->where('order_id',$id)->sum('ysje');
        $xze = round($xsddzje*$xz/100,2);
        //查询已货补的总额
        $this->assign('xze',$xze);

        $uid = session('employee_id');
        $uname = db('employee')->where('id',$uid)->value('em_name');
        $de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
        $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        $this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);
        return $this->fetch();
    }

    /**
     * 补费订单详情
     * @return mixed
     */
    public function bufei_dd_detail(){
        $id = $this->request->param('id');
        if($_POST){
            //验证
            $data = Request::instance()->post();
//            dump($data);
            $valid = new Valid([
                'hxdmxbh|核销明细编号'=>'require',
                'bfje|本次补费金额'=>'require',
                'xsry|销售人员'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
            if($data['bfje']>$data['hxje']){
                echo json_encode(['success'=>false,'msg'=>'本次补费金额不能大于需补费的核销金额']);die;
            }
            if($data['bfje']>$data['kbje']){
                echo json_encode(['success'=>false,'msg'=>'本次补费金额不能大于销售订单可补费金额']);die;
            }
            $max_sn = db('cg_order_list')->where('order_id',$id)->max('sn');
            $max_sn++;
            $data['sn'] = $max_sn;
            $data['xslx'] = 4;
            $bool = db('cg_order_list')->insert($data);

            $yszje = db('cg_order_list')->where('order_id',$id)->sum('ysje');
            $qdyhje = db('cg_order_list')->where('order_id',$id)->sum('qdyhje');
            $bfzje = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->sum('bfje');
            $yszje = $yszje-$qdyhje-$bfzje;
            $yszje = round($yszje,2);
            db('cg_order')->where('id',$id)->update(['yszje'=>$yszje]);

            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'添加成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'添加失败']);die;
            }
            die;
        }
        $uid = session('employee_id');
        $uname = db('employee')->where('id',$uid)->value('em_name');
        $de_name = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$uid)->value('de_name');
        $de_id = db('department_employee')->where('employee_id',$uid)->value('department_id');
        $this->assign([
            'uid'=>$uid,
            'uname'=>$uname,
            'de_name'=>$de_name,
            'de_id'=>$de_id
        ]);

        //销售订单可补费金额（元）
        $dhzje = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>1])->sum('ysje');//订货总金额
        $bhje = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->sum('ysje');//补货总金额
        $bfje = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->sum('bfje');//补费总金额
        //系统设置比例
        $bili = db('system_param')->where(['t'=>0,'k'=>'keDaPercent'])->value('v');
        $dhzje = $dhzje*($bili/100);
        $kbje  = $dhzje-$bhje-$bfje;
        $this->assign('kbje',$kbje);

        return $this->fetch();
    }
    public function delete(){
        $id = $this->request->param('id');
        db('cg_order')->where('id',$id)->delete();
        db('cg_order_list')->where('order_id',$id)->delete();
        echo json_encode(['success'=>true,'msg'=>'删除成功']);
    }
    public function selectJXS(){
        return $this->fetch();
    }
    //查询所有经销商
    public function jxsjson(){
        $jxs_id = $this->request->param('jxs_id');
        $where = [];
        if($jxs_id){
            $where['id'] = $jxs_id;
        }
        //查询所有省份
        $data = db('cg_jxs')->where($where)->select();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    public function getnet($nid){
        $net=db("cg_net")->where(["id"=>$nid])->find();
        $jxs=db("cg_system")->where(["id"=>$net["system_id"]])->value("jxs");
        $net["jxs"]=$jxs;
        return json_encode($net);
    }
    public function getjxs($jid){
        $jxs=db("cg_jxs")->where(["id"=>$jid])->find();
        return json_encode($jxs);
    }
    //判断经销商是否存在渠道优惠政策
    public function hasyh(){
        $jxs_id = $this->request->param('jxs_id');
        $jxs=db("cg_jxs")->where(["id"=>$jxs_id])->field("zoning,provice,city,id")->find();
        //查询是否有渠道优惠政策
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$jxs["zoning"]}\"%') or (area=2 and area_id like '%\"{$jxs["provice"]}\"%') or (area=3 and area_id like '%\"{$jxs["city"]}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id')
            ->count();
        //echo db("cg_channel_preferential_policy")->getLastsql();exit;
        if($qdyhzc){
            echo json_encode(['success'=>true,'msg'=>'存在']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'不存在']);
        }
    }

    //我的销售订单明细查询
    public function wdxsddmxcx(){
        $zoning = $this->request->get('zoning');
        $this->assign('zoning',$zoning);
        $provice = $this->request->get('provice');
        $this->assign('provice',$provice);
        $city = $this->request->get('city');
        $this->assign('city',$city);
        $ordersn = $this->request->get('ordersn');
        $this->assign('ordersn',$ordersn);
        $jxssn = $this->request->get('jxssn');
        $this->assign('jxssn',$jxssn);
        $jxsname = $this->request->get('jxsname');
        $this->assign('jxsname',$jxsname);
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);
        $applyStatus = $this->request->get('applyStatus');
        $this->assign('applyStatus',$applyStatus);
        $wllx = $this->request->get('wllx');
        $this->assign('wllx',$wllx);
        $xslx = $this->request->get('xslx');
        $this->assign('xslx',$xslx);
        $sku = $this->request->get('sku');
        $this->assign('sku',$sku);
        $wlbm = $this->request->get('wlbm');
        $this->assign('wlbm',$wlbm);
        $wlmc = $this->request->get('wlmc');
        $this->assign('wlmc',$wlmc);
        $category = $this->request->get('category');
        $this->assign('category',$category);

        $where = [];
        $where['t2.sqr'] = session('employee_id');
        $cus_ids = [];
        if($zoning){
            $cus_ids = db('cg_market_zoning')->where('title','like',"%{$zoning}%")->column('id');
        }
        if($provice){
            $provice_ids = db('cg_market_provice')->where('title','like',"%{$provice}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$provice_ids):$provice_ids;
        }
        if($city){
            $city_ids = db('cg_market_city')->where('title','like',"%{$city}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$city_ids):$city_ids;
        }
        if($ordersn){
            $where['t2.sn'] = ['like',"%{$ordersn}%"];
        }
        if($jxssn){
            $jxsids = db('cg_jxs')->where('sn','like',"%{$jxssn}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($jxsname){
            $jxsids = db('cg_jxs')->where('title','like',"%{$jxsname}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($applyStatus){
            $where['t2.status'] = $applyStatus;
        }
        $cus_ids = array_unique($cus_ids);
        if($cus_ids){
            $where['t.cusName'] = ['in',$cus_ids];
        }

        $p = [];
        if($wllx){
            $where['t.kind'] = 2;
            $wllxs = db('pro_materials')->where(['m_type'=>2,'material_type_id'=>$wllx])->column('id');
            $where['t.product'] = ['in',$wllxs];
        }

        if($xslx){
            $where['t.kind'] = ['in',$xslx];
        }

        if($sku){
            $products = db('pro_products')->where('sku_id',$sku)->column('id');
            $where['t.kind'] = 1;
            $where['t.product'] = ['in',$products];
        }

        if($wlbm) {
            $products = db('pro_materials')->where('material_no', 'in', "%{$wlbm}%")->column('id');
            $where['t.product'] = ['in', $products];
        }

        if($wlmc){
            $products = db('pro_materials')->where('material_name', 'in', "%{$wlmc}%")->column('id');
            $where['t.product'] = ['in', $products];
        }
        if($category){
            $products = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t.title','like',"%{$category}%")->column('t4.id');
            $where['t.product'] = ['in', $products];
        }
        if($start&&$end){
            $where['t2.jyfhrq'] = [['>',$start],['<',$end],'and'];
        }elseif($start){
            $where['t2.jyfhrq'] = ['>',$start];
        }elseif($end){
            $where['t2.jyfhrq'] = ['<',$end];
        }

        $count = db('cg_order_list t')->join('cg_order t2','t2.id=t.order_id')->where($where)->count();
        $data = db('cg_order_list t')->join('cg_order t2','t2.id=t.order_id')->where($where)->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        $hj1 = 0; //订货数量合计
        $hj2 = 0; //搭赠数量合计
        $hj3 = 0; //应收金额合计
        foreach($data as $k=>$v){
            $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['jxs_sn'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
            $v['jxs_name'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');
            $sku = db('pro_sku t')->join('pro_products t2','t2.sku_id=t.id')->where('t2.id',$v['product'])->field('t.id,t.sku_name')->find();
            $v['sku'] = $sku['sku_name'];
            $series = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.series_name')->find();
            $v['series'] = $series['series_name'];
            $category = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.category_name')->find();
            $v['category'] = $category['category_name'];
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            if($v['kind']==2)
                $v['wllx'] = db('pro_material_type t')->join('pro_materials t2','t2.material_type_id=t.id')->where(['t2.m_type'=>2,'t2.id'=>$v['product']])->value('format');
            else
                $v['wllx'] = '';
            //货补数量
            $v['hbsl'] = db('cg_order_list')->where(['kind'=>$v['kind'],'product'=>$v['product'],'order_id'=>$v['id'],'xslx'=>3])->sum('num');
            $data[$k] = $v;
            $hj1 += $v['num'];
            $hj2 += $v['dzsl'];
            $hj3 += $v['ysje'];
        }
        $hj1 = round($hj1,4);
        $hj2 = round($hj2,4);
        $hj3 = round($hj3,4);
//        dump($data);
        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('maxpage',$maxpage);
        $this->assign('hj1',$hj1);
        $this->assign('hj2',$hj2);
        $this->assign('hj3',$hj3);


        //查询物料类型
        $wllxs = db('pro_material_type')->field('id,type_name')->where('m_type',2)->select();
        $this->assign('wllxs',$wllxs);
        return $this->fetch();
    }

    public function produceSN(){
        //生成编号
        $max = db('cg_order')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }
    public function producemxSN($order_id){
        //生成编号
        $max = db('cg_order_list')->where(['order_id'=>$order_id])->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = 1;
        }
        return $insert_sn;
    }

    //导出我的销售订单列表
    public function excel1(){
        //获取数据
        $zoning = $this->request->get('zoning');
        $provice = $this->request->get('provice');
        $city = $this->request->get('city');
        $ordersn = $this->request->get('ordersn');
        $jxssn = $this->request->get('jxssn');
        $jxsname = $this->request->get('jxsname');
        $start = $this->request->get('start');
        $end = $this->request->get('end');
        $minNum = $this->request->get('minNum');
        $maxNum = $this->request->get('maxNum');
        $applyStatus = $this->request->get('applyStatus');

        $where = [];
        $where['sqr'] = session('employee_id');
        $cus_ids = [];
        if($zoning){
            $cus_ids = db('cg_market_zoning')->where('title','like',"%{$zoning}%")->column('id');
        }
        if($provice){
            $provice_ids = db('cg_market_provice')->where('title','like',"%{$provice}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$provice_ids):$provice_ids;
        }
        if($city){
            $city_ids = db('cg_market_city')->where('title','like',"%{$city}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$city_ids):$city_ids;
        }
        if($ordersn){
            $where['sn'] = ['like',"%{$ordersn}%"];
        }
        if($jxssn){
            $jxsids = db('cg_jxs')->where('sn','like',"%{$jxssn}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($jxsname){
            $jxsids = db('cg_jxs')->where('title','like',"%{$jxsname}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($start&&$end){
            $where['jyfhrq'] = [['>',$start],['<',$end],'and'];
        }elseif($start){
            $where['jyfhrq'] = ['>',$start];
        }elseif($end){
            $where['jyfhrq'] = ['<',$end];
        }
        if($minNum&&$maxNum){
            $where['yszje'] = [['>',$minNum],['<',$maxNum],'and'];
        }elseif($minNum){
            $where['yszje'] = ['>',$minNum];
        }elseif($maxNum){
            $where['yszje'] = ['<',$maxNum];
        }
        if($applyStatus){
            $where['status'] = $applyStatus;
        }
        $cus_ids = array_unique($cus_ids);
        if($cus_ids){
            $where['cusName'] = ['in',$cus_ids];
        }
        $data = db('cg_order')->where($where)->select();
//        echo db('cg_order')->getLastSql();
        foreach($data as $k=>$v){
            $t = $v['cusName'];
            $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$t)->value('t.title');
            $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$t)->value('t.title');
            $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$t)->value('t.title');
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v['jxssn'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
            $v['jxsname'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');
            $data[$k] = $v;
        }

        Vendor("PHPExcel");
        Vendor("PHPExcel.Writer.Excel5");
        $objPHPExcel= new PHPExcel();
        $objProps=$objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $as =  $objPHPExcel->getActiveSheet();
        $title = '我的销售订单';
        $as->setTitle($title);
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
                    'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框
                    'color' => array('argb' => ''),
                ),
            ),
        );
        $as->mergeCells('A1:N1');
        $as->setCellValue('A1',$title);
        //加粗
        $as->getStyle('A1')->getFont()->setBold(true);
        //字体
        $as->getStyle('A1')->getFont()->setSize(14);
        $as->mergeCells('A2:N2');
        $username = db('employee')->where('id',session('employee_id'))->value('em_name');
        $as->setCellValue('A2','注：本表单由软件导出，导出时间：'.date('Y-m-d H:i').'导出人：'.$username);
        $as->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $as->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        //标题
        $as->getStyle('A3:N3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $as->getStyle('A3:N3')->getFill()->getStartColor()->setARGB('0099CCFF');
        $as->setCellValue('A3','NO.');
        $as->setCellValue('B3','分区');
        $as->setCellValue('C3','省份');
        $as->setCellValue('D3','城市');
        $as->setCellValue('E3','时间');
        $as->setCellValue('F3','订单号');
        $as->setCellValue('G3','申请人');
        $as->setCellValue('H3','经销商编号');
        $as->setCellValue('I3','经销商名称');
        $as->setCellValue('J3','渠道优惠政策编号');
        $as->setCellValue('K3','发票类型');
        $as->setCellValue('L3','申请状态');
        $as->setCellValue('M3','箱数');
        $as->setCellValue('N3','金额(元)');

        foreach($data as $k=>$v){
            $n = 4+$k;
            $as->setCellValue('A'.$n,$k+1);
            $as->setCellValue('B'.$n,$v['zoning']);
            $as->setCellValue('C'.$n,$v['provice']);
            $as->setCellValue('D'.$n,$v['city']);
            $as->setCellValue('E'.$n,$v['jyfhrq']);
            $as->setCellValue('F'.$n,$v['sn']);
            $as->setCellValue('G'.$n,$v['sqr']);
            $as->setCellValue('H'.$n,$v['jxssn']);
            $as->setCellValue('I'.$n,$v['jxsname']);
            $as->setCellValue('J'.$n,$v['yhPolicy']);
            $as->setCellValue('K'.$n,$v['fpType']);
            $as->setCellValue('L'.$n,$v['status']);
            $as->setCellValue('M'.$n,'');
            $as->setCellValue('N'.$n,$v['yszje']);
        }

        $n = $as->getHighestRow();
        $as->getStyle('A1:N'.$n)->applyFromArray($styleArray);
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename='.$title.'.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
    //我的销售订单明细
    public function excel2(){
        //获取数据
        $zoning = $this->request->get('zoning');
        $this->assign('zoning',$zoning);
        $provice = $this->request->get('provice');
        $this->assign('provice',$provice);
        $city = $this->request->get('city');
        $this->assign('city',$city);
        $ordersn = $this->request->get('ordersn');
        $this->assign('ordersn',$ordersn);
        $jxssn = $this->request->get('jxssn');
        $this->assign('jxssn',$jxssn);
        $jxsname = $this->request->get('jxsname');
        $this->assign('jxsname',$jxsname);
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);
        $applyStatus = $this->request->get('applyStatus');
        $this->assign('applyStatus',$applyStatus);
        $wllx = $this->request->get('wllx');
        $this->assign('wllx',$wllx);
        $xslx = $this->request->get('xslx');
        $this->assign('xslx',$xslx);
        $sku = $this->request->get('sku');
        $this->assign('sku',$sku);
        $wlbm = $this->request->get('wlbm');
        $this->assign('wlbm',$wlbm);
        $wlmc = $this->request->get('wlmc');
        $this->assign('wlmc',$wlmc);
        $category = $this->request->get('category');
        $this->assign('category',$category);

        $where = [];
        $where['sqr'] = session('employee_id');
        $cus_ids = [];
        if($zoning){
            $cus_ids = db('cg_market_zoning')->where('title','like',"%{$zoning}%")->column('id');
        }
        if($provice){
            $provice_ids = db('cg_market_provice')->where('title','like',"%{$provice}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$provice_ids):$provice_ids;
        }
        if($city){
            $city_ids = db('cg_market_city')->where('title','like',"%{$city}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$city_ids):$city_ids;
        }
        if($ordersn){
            $where['t2.sn'] = ['like',"%{$ordersn}%"];
        }
        if($jxssn){
            $jxsids = db('cg_jxs')->where('sn','like',"%{$jxssn}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($jxsname){
            $jxsids = db('cg_jxs')->where('title','like',"%{$jxsname}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($applyStatus){
            $where['t2.status'] = $applyStatus;
        }
        $cus_ids = array_unique($cus_ids);
        if($cus_ids){
            $where['t.cusName'] = ['in',$cus_ids];
        }

        $p = [];
        if($wllx){
            $where['t.kind'] = 2;
            $wllxs = db('pro_materials')->where(['m_type'=>2,'material_type_id'=>$wllx])->column('id');
            $where['t.product'] = ['in',$wllxs];
        }

        if($xslx){
            $where['t.kind'] = ['in',$xslx];
        }

        if($sku){
            $products = db('pro_products')->where('sku_id',$sku)->column('id');
            $where['t.kind'] = 1;
            $where['t.product'] = ['in',$products];
        }

        if($wlbm) {
            $products = db('pro_materials')->where('material_no', 'in', "%{$wlbm}%")->column('id');
            $where['t.product'] = ['in', $products];
        }

        if($wlmc){
            $products = db('pro_materials')->where('material_name', 'in', "%{$wlmc}%")->column('id');
            $where['t.product'] = ['in', $products];
        }
        if($category){
            $products = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t.title','like',"%{$category}%")->column('t4.id');
            $where['t.product'] = ['in', $products];
        }
        if($start&&$end){
            $where['t2.jyfhrq'] = [['>',$start],['<',$end],'and'];
        }elseif($start){
            $where['t2.jyfhrq'] = ['>',$start];
        }elseif($end){
            $where['t2.jyfhrq'] = ['<',$end];
        }

        $data = db('cg_order_list t')->join('cg_order t2','t2.id=t.order_id')->where($where)->select();
        $hj1 = 0; //订货数量合计
        $hj2 = 0; //搭赠数量合计
        $hj3 = 0; //应收金额合计
        foreach($data as $k=>$v){
            $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['jxs_sn'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
            $v['jxs_name'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');
            $sku = db('pro_sku t')->join('pro_products t2','t2.sku_id=t.id')->where('t2.id',$v['product'])->field('t.id,t.sku_name')->find();
            $v['sku'] = $sku['sku_name'];
            $series = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.series_name')->find();
            $v['series'] = $series['series_name'];
            $category = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.category_name')->find();
            $v['category'] = $category['category_name'];
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            if($v['kind']==2)
                $v['wllx'] = db('pro_material_type t')->join('pro_materials t2','t2.material_type_id=t.id')->where(['m_type'=>2,$v['product']])->value('format');
            else
                $v['wllx'] = '';
            //货补数量
            $v['hbsl'] = db('cg_order_list')->where(['kind'=>$v['kind'],'prod_id'=>$v['product'],'order_id'=>$v['id'],'xslx'=>3])->sum('num');
            $data[$k] = $v;
            $hj1 += $v['num'];
            $hj2 += $v['dzsl'];
            $hj3 += $v['ysje'];
        }
        $hj1 = round($hj1,4);
        $hj2 = round($hj2,4);
        $hj3 = round($hj3,4);
//        dump($data);
        $this->assign('data',$data);
        $this->assign('hj1',$hj1);
        $this->assign('hj2',$hj2);
        $this->assign('hj3',$hj3);

        Vendor("PHPExcel");
        Vendor("PHPExcel.Writer.Excel5");
        $objPHPExcel= new PHPExcel();
        $objProps=$objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $as =  $objPHPExcel->getActiveSheet();
        $title = '我的销售订单明细查询';
        $as->setTitle($title);
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
                    'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框
                    'color' => array('argb' => ''),
                ),
            ),
        );
        $as->mergeCells('A1:AA1');
        $as->setCellValue('A1',$title);
        //加粗
        $as->getStyle('A1')->getFont()->setBold(true);
        //字体
        $as->getStyle('A1')->getFont()->setSize(14);
        $as->mergeCells('A2:AA2');
        $username = db('employee')->where('id',session('employee_id'))->value('em_name');
        $as->setCellValue('A2','注：本表单由软件导出，导出时间：'.date('Y-m-d H:i').'导出人：'.$username);
        $as->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $as->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        //标题
        $as->getStyle('A3:AA3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $as->getStyle('A3:AA3')->getFill()->getStartColor()->setARGB('0099CCFF');
        $as->setCellValue('A3','NO.');
        $as->setCellValue('B3','分区');
        $as->setCellValue('C3','省份');
        $as->setCellValue('D3','城市');
        $as->setCellValue('E3','时间');
        $as->setCellValue('F3','对应销售订单编号');
        $as->setCellValue('G3','经销商编号');
        $as->setCellValue('H3','经销商名称');
        $as->setCellValue('I3','申请状态');
        $as->setCellValue('J3','品类');
        $as->setCellValue('K3','SKU');
        $as->setCellValue('L3','物料编码');
        $as->setCellValue('M3','物料名称');
        $as->setCellValue('N3','规格');
        $as->setCellValue('O3','物料类型');
        $as->setCellValue('P3','销售类型');
        $as->setCellValue('Q3','单位');
        $as->setCellValue('R3','供货单位（元）');
        $as->setCellValue('S3','订货数量');
        $as->setCellValue('T3','搭赠数量');
        $as->setCellValue('U3','货补数量');
        $as->setCellValue('V3','发货数量');
        $as->setCellValue('W3','收货数量');
        $as->setCellValue('X3','原金额（元）');
        $as->setCellValue('Y3','应收金额（元）');
        $as->setCellValue('Z3','体积（立方米）');
        $as->setCellValue('AA3','重量（吨）');

        foreach($data as $k=>$v){
            $n = 4+$k;
            $as->setCellValue('A'.$n,$k+1);
            $as->setCellValue('B'.$n,$v['zoning']);
            $as->setCellValue('C'.$n,$v['provice']);
            $as->setCellValue('D'.$n,$v['city']);
            $as->setCellValue('E'.$n,$v['jyfhrq']);
            $as->setCellValue('F'.$n,$v['sn']);
            $as->setCellValue('G'.$n,$v['jxs_sn']);
            $as->setCellValue('H'.$n,$v['jxs_name']);
            $as->setCellValue('I'.$n,$v['status']);
            $as->setCellValue('J'.$n,$v['category']);
            $as->setCellValue('K'.$n,$v['sku']);
            $as->setCellValue('L'.$n,$v['prod_sn']);
            $as->setCellValue('M'.$n,$v['pro_name']);
            $as->setCellValue('N'.$n,$v['format']);
            $as->setCellValue('O'.$n,$v['wllx']);
            $as->setCellValue('P'.$n,$v['kind']==1?'成品':'销售物料');
            $as->setCellValue('Q'.$n,$v['unit']);
            $as->setCellValue('R'.$n,$v['xgj']);
            $as->setCellValue('S'.$n,$v['num']);
            $as->setCellValue('T'.$n,$v['dzsl']);
            $as->setCellValue('U'.$n,$v['hbsl']);
            $as->setCellValue('V'.$n,$v['fhsl']);
            $as->setCellValue('W'.$n,$v['shsl']);
            $as->setCellValue('X'.$n,$v['yje']);
            $as->setCellValue('Y'.$n,$v['ysje']);
            $as->setCellValue('Z'.$n,$v['tj']);
            $as->setCellValue('AA'.$n,$v['zl']);
        }

        $n = $as->getHighestRow();
        $as->getStyle('A1:AA'.$n)->applyFromArray($styleArray);
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename='.$title.'.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    /**
     * 所属销售订单
     */
    public function ssxsdd(){
        $status = $this->request->param('status');
        $zoning = $this->request->param('zoning');
        $provice = $this->request->param('provice');
        $city = $this->request->param('city');
        $sn = $this->request->param('sn');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $sqrmc = $this->request->param('sqrmc');
        $khbh = $this->request->param('khbh');
        $khmc = $this->request->param('khmc');
        $minNum = $this->request->param('minNum');
        $maxNum = $this->request->param('maxNum');
        $yhPolicymc = $this->request->param('yhPolicymc');
        $this->assign('status',$status);
        $this->assign('zoning',$zoning);
        $this->assign('provice',$provice);
        $this->assign('city',$city);
        $this->assign('sn',$sn);
        $this->assign('start',$start);
        $this->assign('end',$end);
        $this->assign('sqrmc',$sqrmc);
        $this->assign('khbh',$khbh);
        $this->assign('khmc',$khmc);
        $this->assign('minNum',$minNum);
        $this->assign('maxNum',$maxNum);
        $this->assign('yhPolicymc',$yhPolicymc);
        $where = [];
        if($status){
            $where['status'] = $status;
        }
        if($zoning){
            $where['zoning'] = ['like','%'.$zoning.'%'];
        }
        if($provice){
            $where['provice'] = ['like','%'.$provice.'%'];
        }
        if($city){
            $where['city'] = ['like','%'.$city.'%'];
        }
        if($sn){
            $where['sn'] = ['like','%'.$sn.'%'];
        }
        if($start&&!$end){
            $where['sqrq'] = ['>',strtotime($start)];
        }elseif(!$start&&$end){
            $where['sqrq'] = ['<',strtotime($end)];
        }elseif($start&&$end){
            $where['sqrq'] = [['>',strtotime($start)],['<',strtotime($end)],'and'];
        }
        if($sqrmc){
            $where['sqrmc'] = ['like','%'.$sqrmc.'%'];
        }
        if($sqrmc){
            $where['sqrmc'] = ['like','%'.$sqrmc.'%'];
        }
        if($khbh){
            $where['khbh'] = ['like','%'.$khbh.'%'];
        }
        if($khmc){
            $where['khmc'] = ['like','%'.$khmc.'%'];
        }
        if($minNum&&!$maxNum){
            $where['yszje'] = ['>',strtotime($minNum)];
        }elseif(!$minNum&&$maxNum){
            $where['yszje'] = ['<',strtotime($maxNum)];
        }elseif($minNum&&$maxNum){
            $where['yszje'] = [['>',strtotime($minNum)],['<',strtotime($maxNum)],'and'];
        }
        if($sqrmc){
            $where['yhPolicymc'] = ['like','%'.$yhPolicymc.'%'];
        }
        $count = db('cg_order')->where($where)->count();
        $data = db('cg_order')->where($where)->order('sqrq desc')->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
		$maxpage=ceil($count/10);	
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('maxpage',$maxpage);
        foreach($data as $k=>$v){
            if($v['cusType']==1){

                $v['jxsbh'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
                $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['cusName'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');

            }else{

                $v['jxsbh'] = db('cg_net')->where('id',$v['cusName'])->value('sn');
                $v['zoning'] = db('cg_market_zoning t')->join('cg_net t2','t2.zoning=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$v['cusName'])->value('t.title');
                $v['cusName'] = db('cg_net')->where('id',$v['cusName'])->value('title');

            }
            $v['sqrq'] = date('Y-m-d',$v['sqrq']);
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v['yhPolicy'] = db('cg_channel_preferential_policy')->where('id',$v['yhPolicy'])->value('title');
            $data[$k] = $v;
        }
        $this->assign('data',$data);
        return $this->fetch();
    }

    //所属销售订单明细查询
    public function ssxsddmxcx(){
        $zoning = $this->request->get('zoning');
        $this->assign('zoning',$zoning);
        $provice = $this->request->get('provice');
        $this->assign('provice',$provice);
        $city = $this->request->get('city');
        $this->assign('city',$city);
        $ordersn = $this->request->get('ordersn');
        $this->assign('ordersn',$ordersn);
        $jxssn = $this->request->get('jxssn');
        $this->assign('jxssn',$jxssn);
        $jxsname = $this->request->get('jxsname');
        $this->assign('jxsname',$jxsname);
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);
        $applyStatus = $this->request->get('applyStatus');
        $this->assign('applyStatus',$applyStatus);
        $wllx = $this->request->get('wllx');
        $this->assign('wllx',$wllx);
        $xslx = $this->request->get('xslx');
        $this->assign('xslx',$xslx);
        $sku = $this->request->get('sku');
        $this->assign('sku',$sku);
        $wlbm = $this->request->get('wlbm');
        $this->assign('wlbm',$wlbm);
        $wlmc = $this->request->get('wlmc');
        $this->assign('wlmc',$wlmc);
        $category = $this->request->get('category');
        $this->assign('category',$category);

        $where = [];
        $where['t2.sqr'] = session('employee_id');
        $cus_ids = [];
        if($zoning){
            $cus_ids = db('cg_market_zoning')->where('title','like',"%{$zoning}%")->column('id');
        }
        if($provice){
            $provice_ids = db('cg_market_provice')->where('title','like',"%{$provice}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$provice_ids):$provice_ids;
        }
        if($city){
            $city_ids = db('cg_market_city')->where('title','like',"%{$city}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$city_ids):$city_ids;
        }
        if($ordersn){
            $where['t2.sn'] = ['like',"%{$ordersn}%"];
        }
        if($jxssn){
            $jxsids = db('cg_jxs')->where('sn','like',"%{$jxssn}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($jxsname){
            $jxsids = db('cg_jxs')->where('title','like',"%{$jxsname}%")->column('id');
            $cus_ids = $cus_ids?array_intersect($cus_ids,$jxsids):$jxsids;
        }
        if($applyStatus){
            $where['t2.status'] = $applyStatus;
        }
        $cus_ids = array_unique($cus_ids);
        if($cus_ids){
            $where['t.cusName'] = ['in',$cus_ids];
        }

        $p = [];
        if($wllx){
            $where['t.kind'] = 2;
            $wllxs = db('pro_materials')->where(['m_type'=>2,'material_type_id'=>$wllx])->column('id');
            $where['t.product'] = ['in',$wllxs];
        }

        if($xslx){
            $where['t.kind'] = ['in',$xslx];
        }

        if($sku){
            $products = db('pro_products')->where('sku_id',$sku)->column('id');
            $where['t.kind'] = 1;
            $where['t.product'] = ['in',$products];
        }

        if($wlbm) {
            $products = db('pro_materials')->where('material_no', 'in', "%{$wlbm}%")->column('id');
            $where['t.product'] = ['in', $products];
        }

        if($wlmc){
            $products = db('pro_materials')->where('material_name', 'in', "%{$wlmc}%")->column('id');
            $where['t.product'] = ['in', $products];
        }
        if($category){
            $products = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t.title','like',"%{$category}%")->column('t4.id');
            $where['t.product'] = ['in', $products];
        }
        if($start&&$end){
            $where['t2.jyfhrq'] = [['>',$start],['<',$end],'and'];
        }elseif($start){
            $where['t2.jyfhrq'] = ['>',$start];
        }elseif($end){
            $where['t2.jyfhrq'] = ['<',$end];
        }

        $count = db('cg_order_list t')->join('cg_order t2','t2.id=t.order_id')->where($where)->count();
        $data = db('cg_order_list t')->join('cg_order t2','t2.id=t.order_id')->where($where)->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);	
        $hj1 = 0; //订货数量合计
        $hj2 = 0; //搭赠数量合计
        $hj3 = 0; //应收金额合计
        foreach($data as $k=>$v){
            $v['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$v['cusName'])->value('t.title');
            $v['jxs_sn'] = db('cg_jxs')->where('id',$v['cusName'])->value('sn');
            $v['jxs_name'] = db('cg_jxs')->where('id',$v['cusName'])->value('title');
            $sku = db('pro_sku t')->join('pro_products t2','t2.sku_id=t.id')->where('t2.id',$v['product'])->field('t.id,t.sku_name')->find();
            $v['sku'] = $sku['sku_name'];
            $series = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.series_name')->find();
            $v['series'] = $series['series_name'];
            $category = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sku['id'])->field('t.id,t.category_name')->find();
            $v['category'] = $category['category_name'];
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            if($v['kind']==2)
                $v['wllx'] = db('pro_material_type t')->join('pro_materials t2','t2.material_type_id=t.id')->where(['m_type'=>2,$v['product']])->value('format');
            else
                $v['wllx'] = '';
            //货补数量
            $v['hbsl'] = db('cg_order_list')->where(['kind'=>$v['kind'],'prod_id'=>$v['product'],'order_id'=>$v['id'],'xslx'=>3])->sum('num');
            $data[$k] = $v;
            $hj1 += $v['num'];
            $hj2 += $v['dzsl'];
            $hj3 += $v['ysje'];
        }
        $hj1 = round($hj1,4);
        $hj2 = round($hj2,4);
        $hj3 = round($hj3,4);
//        dump($data);
        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('maxpage',$maxpage);
        $this->assign('hj1',$hj1);
        $this->assign('hj2',$hj2);
        $this->assign('hj3',$hj3);


        //查询物料类型
        $wllxs = db('pro_material_type')->field('id,type_name')->where('m_type',2)->select();
        $this->assign('wllxs',$wllxs);
        return $this->fetch();
    }

    /**
     * 所属销售订单汇总表
     */
    public function ssxsddhzb(){
        $zoning = $this->request->param('zoning');
        $provice = $this->request->param('provice');
        $city = $this->request->param('city');
        $khbh = $this->request->param('khbh');
        $khmc = $this->request->param('khmc');
        $brand = $this->request->param('brand');
        $category = $this->request->param('category');
        $series = $this->request->param('series');
        $sku = $this->request->param('sku');
        $prod_sn = $this->request->param('prod_sn');
        $prod_name = $this->request->param('prod_name');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $this->assign('zoning',$zoning);
        $this->assign('provice',$provice);
        $this->assign('city',$city);
        $this->assign('khbh',$khbh);
        $this->assign('khmc',$khmc);
        $this->assign('brand',$brand);
        $this->assign('category',$category);
        $this->assign('series',$series);
        $this->assign('sku',$sku);
        $this->assign('prod_sn',$prod_sn);
        $this->assign('prod_name',$prod_name);
        $this->assign('start',$start);
        $this->assign('end',$end);
        $where = [];
        if($zoning){
            $where['t.zoning'] = ['like','%'.$zoning.'%'];
        }
        if($provice){
            $where['t.provice'] = ['like','%'.$provice.'%'];
        }
        if($city){
            $where['t.city'] = ['like','%'.$city.'%'];
        }
        if($khbh){
            $where['t.khbh'] = ['like','%'.$khbh.'%'];
        }
        if($khmc){
            $where['t.khmc'] = ['like','%'.$khmc.'%'];
        }
        if($brand){
            $where['t2.brand'] = ['like','%'.$brand.'%'];
        }
        if($category){
            $where['t2.category'] = ['like','%'.$category.'%'];
        }
        if($series){
            $where['t2.series'] = ['like','%'.$series.'%'];
        }
        if($sku){
            $where['t2.sku'] = ['like','%'.$sku.'%'];
        }
        if($prod_sn){
            $where['t2.prod_sn'] = ['like','%'.$prod_sn.'%'];
        }
        if($prod_name){
            $where['t2.prod_name'] = ['like','%'.$prod_name.'%'];
        }
        if($start&&!$end){
            $where['t.sqrq'] = ['>',strtotime($start)];
        }elseif(!$start&&$end){
            $where['t.sqrq'] = ['<',strtotime($end)];
        }elseif(!$start&&$end){
            $where['t.sqrq'] = [['>',strtotime($start)],['<',strtotime($end)],'and'];
        }

        $count  = db('cg_order t')->join('cg_order_list t2','t2.order_id=t.id')->group('product')->where($where)->count();
        $data  = db('cg_order t')->join('cg_order_list t2','t2.order_id=t.id')->group('product')->where($where)->field('sum(num) num,sum(dzsl) dzsl,sum(ysje) ysje,product,category,sku,prod_name,unit')->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('maxpage',$maxpage);
        foreach($data as $k=>$v){
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $data[$k] = $v;
        }
        $this->assign('data',$data);
        return $this->fetch();
    }
    /*
    清空优惠政策    
     */
    public function clearyh($oid){
        try{
             $bool = db('cg_order')->where('id',$oid)->update(['yhPolicy'=>0,'yhPolicymc'=>null]);
            $qdyhje = db('cg_order_list')->where(['order_id'=>$oid])->sum('qdyhje');
            db('cg_order')->where(['id'=>$oid])->setInc('yszje',$qdyhje);
           
            db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$oid and xslx=1");
           
            db('cg_order_list')->where(['order_id'=>$oid,'sfqdzp'=>1])->delete();
        }catch (\Exception $e) {
             echo json_encode(['success'=>false,'msg'=>$e->getMessage()]);die;
        }
        echo json_encode(['success'=>true,'msg'=>'ok']);die;
        
        
    }
    /*
    切换用户
     */
    public function changecus($cusType,$cusName,$oid){
        try{
            $data["cusType"]=$cusType;
            $data["cusName"]=$cusName;
            $data["yhPolicy"]=0;
            $data["yhPolicymc"]=null;
            if($cusType==1){
                //jxs
                $jid=$cusName;
                $jxs=db("cg_jxs")->where(["id"=>$cusName])->find();
                $data["khbh"]=$jxs["sn"];
                $data["khmc"]=$jxs["title"];
                $data["shdz"]=$jxs["bs_rcv_addr"];
                $data["shr"]=$jxs["bs_rcv_one"];
                $data["dh"]=$jxs["bs_rcv_phone"];
                $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
                $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
                $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
            }else{
                //net
                $net=db("cg_net")->where(["id"=>$cusName])->find();
                $data["khbh"]=$net["sn"];
                $data["khmc"]=$net["title"];
                $data["shdz"]=$net["lgs_rcv_addr"];
                $data["shr"]=$net["lgs_rcv_one"];
                $data["dh"]=$net["lgs_rcv_phone"];
                $jid=db("cg_system")->where(["id"=>$net["system_id"]])->value("jxs");
                $jxs=db("cg_jxs")->where(["id"=>$jid])->find();
                $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
                $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
                $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
            }
            db("cg_order_list")->where("order_id=$oid and xslx<>1")->delete();
            $odl=db("cg_order_list")->where("order_id=$oid and xslx=1")->select();
            $data["yszje"]=0;
            foreach ($odl as $k => $v) {
                # code...
                if($v["kind"]==1){
                    $pid=$v["product"];
                    $pro=$this->getprice($jid,$pid);
                    $oldata["unit"]=$pro["unit"];
                    $oldata["ygj"]=$pro["price"];
                    $oldata["xgj"]=$pro["price"];
                    $oldata["qdyhje"]=null;$oldata["qdyhms"]=null;
                    if($v["num"]){
                        $oldata["yje"]=$oldata["xgj"]*$v["num"];
                        $oldata["ysje"]=$oldata["xgj"]*$v["num"];
                    }else{
                        $oldata["yje"]=$oldata["xgj"]*$v["dzsl"];
                        $oldata["ysje"]=0;
                    }
                    db("cg_order_list")->where(["id"=>$v["id"]])->update($oldata);
                    $data["yszje"]+=$oldata["ysje"];
                }else{
                    $data["yszje"]+=$v["ysje"];
                }
                
            }
            db("cg_order")->where(["id"=>$oid])->update($data);
        }catch (\Exception $e) {
             echo json_encode(['success'=>false,'msg'=>$e->getMessage()]);die;
        }
        echo json_encode(['success'=>true,'msg'=>'ok']);die;
        

    }
    public function getprice($jid,$pid){
        $unitid=db("pro_products")->where(["id"=>$pid])->value("base_unit_id");
        if($unitid==1){
            $price=db("pro_price")->where(["pid"=>$pid])->value("box_factory");
            $data["unit"]="箱";
        }else{
            $price=db("pro_price")->where(["pid"=>$pid])->value("factory");
            $data["unit"]=db("pro_products")->where(["id"=>$pid])->value("unit");
        }
        $gid=db("price_group_jxs pj")->join("pro_price_group p","pj.gid=p.id")->where("pj.jid=$jid")->value("pj.gid");
        if($gid){
            $now=date("Y-m-d");
            $gp=db("price_group_product")->where("pid=$pid and gid=$gid and start_time<='$now' and end_time>='$now'")->find();
            if($gp){
                if($unitid==1){
                    $price=$gp["fayun_price"];
                }else{
                    $price=$gp["lingshou_price"];
                }
            }
            
        }
        $data["price"]=$price;
        return $data;
    }
    /**
     * 查询渠道优惠政策限制并计算订单金额
     */
    public function qdyhzcxz(){
        $qdyh_id = $this->request->param('qdyh_id');
        $order_id = $this->request->param('order_id');
        $qdyh_name=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$qdyh_id)->value('p.title');
        $qid=db("cg_channel_preferential_policy_cxfa")->where(["id"=>$qdyh_id])->value("p_id");
        $fanganno=db("cg_channel_preferential_policy_cxfa")->where("id<=$qdyh_id and p_id=$qid")->count();
        $bool = db('cg_order')
            ->where('id',$order_id)
            ->update([
                'yhPolicy'=>$qdyh_id,
                'yhPolicymc'=>$qdyh_name.'-促销方案'.$fanganno
            ]);
       // echo $bool;exit;
        //订单明细应用渠道优惠规则
        $khxx = db('cg_order')->where(['id'=>$order_id])->field('cusType,cusName')->find();
        if($khxx['cusType']==1){ //经销商
            //查询经销商所在的大区省份城市
            $jxs = $khxx['cusName'];
            $city = db('cg_jxs')->where('id',$khxx['cusName'])->value('city');
            $provice = db('cg_jxs')->where('id',$khxx['cusName'])->value('provice');
            $zoning = db('cg_jxs')->where('id',$khxx['cusName'])->value('zoning');

        }else{ //网点
            $jxs = db('cg_net t')->join('cg_system t2','t2.id=t.system_id')->where('t.id',$khxx['cusName'])->value('t2.jxs');
            $city = db('cg_jxs')->where('id',$jxs)->value('city');
            $provice = db('cg_jxs')->where('id',$jxs)->value('provice');
            $zoning = db('cg_jxs')->where('id',$jxs)->value('zoning');
        }

        //查询渠道优惠政策的明细
        $qdmx2 = Db::query('select sfzd,product,product_id,yhlx,chzk_unit,chzk_reach,chzk_down,chzk_limit,agdjch_unit,agdjch_reach,agdjch_down,agdjch_limit,shdz_unit,shdz_reach,shdz_gift,shdz_limit,shmj_unit,shmj_reach,shmj_down,shmj_limit,chfd_unit,chfd_reach,chfd_down,chfd_limit 
from cg_channel_preferential_policy_cxfa 
where id='.$qdyh_id.' 
and start <= \''.date('Y-m-d').'\' 
and `end` >=\''.date('Y-m-d').'\' 
and ((area=1 and area_id like \'%"'.$zoning.'"%\') or (area=2 and area_id like \'%"'.$provice.'"%\') or (area=3 and area_id like \'%"'.$city.'"%\')or (area=4 and area_id like \'%"'.$jxs.'"%\'))');//非整单优惠政策明细信息
        //print_r($qdmx2);exit;
        /**
         * 明细套用渠道优惠政策--start
         */
        $mx = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->select();
        $qdyhje = db('cg_order_list')->where(['order_id'=>$order_id])->sum('qdyhje');
        db('cg_order')->where(['id'=>$order_id])->setInc('yszje',$qdyhje);
       // db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->update(['qdyhje'=>0,'qdyhms'=>null]);
        db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$order_id and xslx=1");
        //echo db('cg_order_list')->getLastSql();exit;
        db('cg_order_list')->where(['order_id'=>$order_id,'sfqdzp'=>1])->delete();


        foreach($mx as $k=>$v){
            $v['id'];
            $ysje = $v['yje'];
            $ysjes=$ysje;
            //echo $ysje;exit;
            $qdyhms = '';
            $num=$v['num'];
            $v['kind']==1;
            $product = $v['product'];
            $sku = db('pro_products')->where('id',$v['product'])->value('sku_id');
            $series_id = db('pro_sku')->where('id',$sku)->value('series_id');
            $category_id = db('pro_series')->where('id',$series_id)->value('category_id');
            $brand_id = db('pro_category')->where('id',$category_id)->value('brand_id');
            foreach($qdmx2 as $k2=>$v2){
                if($v2['sfzd'] == 0){ //非整单
                    //判断产品是否符合渠道优惠政策的条件
                    if(
                        ($v2['product']==5&&in_array($product,unserialize($v2['product_id'])))
                        || ($v2['product']==1&&in_array($brand_id,unserialize($v2['product_id'])))
                        || ($v2['product']==2&&in_array($category_id,unserialize($v2['product_id'])))
                        || ($v2['product']==3&&in_array($series_id,unserialize($v2['product_id'])))
                        || ($v2['product']==4&&in_array($sku,unserialize($v2['product_id'])))
                    ){
                        if(in_array(3,unserialize($v2['yhlx']))){ //出货折扣
                            $reach = unserialize($v2['chzk_reach']);
                            $down = unserialize($v2['chzk_down']);
                            $limit = unserialize($v2['chzk_limit']);
                            $unit = $v2['chzk_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   // echo $reach[$key];exit;
                                    $yhje = round($ysjes*$down[$key]/100,2);

                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    //echo $yhje;exit;
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                   
                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=round($num*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($jiannum>$limit[$key]){
                                            $jiannum= $limit[$key];
                                        }
                                    }
                                    $yhje = round($jiannum*$v["xgj"],2);
                                    //echo $yhje;
                                    
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                  
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }

                        if(in_array(4,unserialize($v2['yhlx']))){ //按固定价出货
                            $reach = unserialize($v2['agdjch_reach']);
                            $down = unserialize($v2['agdjch_down']);
                            $limit = unserialize($v2['agdjch_limit']);
                            $unit = $v2['agdjch_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = $num*$down[$key];
                                    $sxje = $ysje-$yhje; //省下金额
                                    //echo $sxje;exit;
                                    if($limit[$key]){
                                         if($sxje>$limit[$key]){
                                            $sxje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);

                                   
                                    $ysje = $ysje-$sxje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    //echo $limit[$key];
                                    $limit[$key];
                                    if($limit[$key]){
                                        if($num>$limit[$key]){
                                            $sxje = ($v['xgj']-$down[$key])*$limit[$key];
                                        }else{ //完全按照新价格计算优惠金额
                                            $yhje = $num*$down[$key];
                                            $sxje = $ysjes-$yhje; //省下金额

                                        }
                                    }else{
                                        $yhje = $num*$down[$key];
                                        $sxje = $ysjes-$yhje; //省下金额
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);


                                    $ysje = $ysje-$sxje;
                                }
                            }
                        }

                        if(in_array(5,unserialize($v2['yhlx']))){ //随货搭赠
                            //echo 5;
                            $reach = unserialize($v2['shdz_reach']);
                            $down = unserialize($v2['shdz_gift']);
                            $limit = unserialize($v2['shdz_limit']);
                            $unit = $v2['shdz_unit'];
                            if($unit=='元'){

                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);
//                                $gift = str_replace('"',"'",$gift);

                                    $gift = json_decode($gift);
                                    $zongbujin=0;

                                    foreach ($gift as $gk => $gv) {
                                        # code...
                                        $zongbujin+=$gv->total;
                                    }
                                    $buhuojine=round($ysjes/$reach[$key],2)*$zongbujin;
                                    if($limit[$key]){
                                        $buhuojine=$buhuojine<=$limit[$key]?$buhuojine:$limit[$key];
                                    }
                                    $beishu=round($buhuojine/$zongbujin,2);
                                    //echo $beishu;//exit;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                       // echo 1;
                                        $ins = [];
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;

                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = floor($gv->num*$beishu);
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = floor($gv->num*$beishu)*$gv->price;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);

                                        $zj += $ins['yje'];
                                        if($limit[$key]){
                                            if($zj>$limit[$key]){
                                                continue;
                                            }
                                        }
                                        

                                        db('cg_order_list')->insert($ins);
                                    }
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);

                                    $gift = json_decode($gift);
                                    $jiannum=$num;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    $beishu=floor($jiannum/$reach[$key]);
                                    //echo $beishu;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;
                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = $gv->num*$beishu;
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = $gv->total*$beishu;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);
                                        $zj += $ins['yje'];
                                        
                                        db('cg_order_list')->insert($ins);
                                    }

                                }
                            }
                        }

                        if(in_array(1,unserialize($v2['yhlx']))){ //随货满减
                            
                            $reach = unserialize($v2['shmj_reach']);
                            $down = unserialize($v2['shmj_down']);
                            $limit = unserialize($v2['shmj_limit']);
                            $unit = $v2['shmj_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jianjine=floor($ysjes/$reach[$key])*$down[$key];
                                    //echo $jianjine;exit;
                                    if($limit[$key]){
                                        $jianjine=$jianjine<=$limit[$key]?$jianjine:$limit[$key];
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jianjine);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jianjine);


                                    $ysje = $ysje-$jianjine;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=floor($num/$reach[$key])*$down[$key];

                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    //echo $jiannum;exit;
                                    $jian =$jiannum*$v['xgj'];
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                    
                                    $ysje = $ysje-$jian;
                                }
                            }
                        }

                        if(in_array(2,unserialize($v2['yhlx']))){ //出货返点

                            $reach = unserialize($v2['chfd_reach']);
                            $down = unserialize($v2['chfd_down']);
                            $limit = unserialize($v2['chfd_limit']);
                            $unit = $v2['chfd_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = round($ysjes*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   $jiannum=round($num*$down[$key]/100,2);
                                    //echo $jiannum;exit;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    
                                    $yhje =$jiannum*$v['xgj'];
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }
                        $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                        db('cg_order')
                            ->where('id',$v['order_id'])
                            ->setDec('yszje',$qdyhzcje);
                    }
                }else{ //整单

                    if(in_array(1,unserialize($v2['yhlx']))){ //随货满减

                        $reach = unserialize($v2['shmj_reach']);
                        $down = unserialize($v2['shmj_down']);
                        $limit = unserialize($v2['shmj_limit']);
                        $unit = $v2['shmj_unit'];//echo $ysje;exit;
                       // echo 1;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];

                                $jisuanjine=floor($ysjes/$reach[$key])*$down[$key];
                                if($limit[$key])
                                    $jisuanjine=$jisuanjine<=$limit[$key]?$jisuanjine:$limit[$key];
                                //echo $jisuanjine;exit;
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                               
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jisuanjine);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jisuanjine);
                                $ysje = $ysje-$jisuanjine;
                            }
                        }else{ //发运单位
                            echo 1;
                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $jiannum=floor($num/$reach[$key])*$down[$key];

                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                //echo $jiannum;exit;
                                $jian =$jiannum*$v['xgj'];
                               //echo $jian.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }
                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                $ysje = $ysje-$jian;
                            }
                        }
                    }

                    if(in_array(2,unserialize($v2['yhlx']))){ //出货返点
                        
                        $reach = unserialize($v2['chfd_reach']);
                        $down = unserialize($v2['chfd_down']);
                        $limit = unserialize($v2['chfd_limit']);
                        $unit = $v2['chfd_unit'];
                        //echo $ysje;exit;
                        //echo 2;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $yhje = round($ysjes*$down[$key]/100,2);
                                //echo $yhje;exit;
                                if($limit[$key]){
                                    if($yhje>$limit[$key]){
                                        $yhje = $limit[$key];
                                    }
                                }
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                //echo $yhje;exit;
                                db('cg_order_list')->where("id={$v["id"]}")->setInc('qdyhje',$yhje);//echo 1;exit;

                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }else{ //发运单位

                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);
                            //echo $max;exit;
                            if($max){

                                $key=array_search($max ,$reach);

                                $down[$key];
                                $limit[$key];
                                $jiannum=round($num*$down[$key]/100,2);
                                //echo $jiannum;exit;
                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                
                                $yhje =$jiannum*$v['xgj'];
                                //echo $yhje.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }
                                 db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }
                    }

                    $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                    db('cg_order')
                        ->where('id',$v['order_id'])
                        ->setDec('yszje',$qdyhzcje);
                }

            }
        }
        /**
         * 明细套用渠道优惠政策--end
         */

        if($bool !== false){
            echo json_encode(['success'=>true,'msg'=>'ok']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);die;
        }
    }

    function unescape($str)
    {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i ++)
        {
            if ($str[$i] == '%' && $str[$i + 1] == 'u')
            {
                $val = hexdec(substr($str, $i + 2, 4));
                if ($val < 0x7f)
                    $ret .= chr($val);
                else
                    if ($val < 0x800)
                        $ret .= chr(0xc0 | ($val >> 6)) .
                            chr(0x80 | ($val & 0x3f));
                    else
                        $ret .= chr(0xe0 | ($val >> 12)) .
                            chr(0x80 | (($val >> 6) & 0x3f)) .
                            chr(0x80 | ($val & 0x3f));
                $i += 5;
            } else
                if ($str[$i] == '%')
                {
                    $ret .= urldecode(substr($str, $i, 3));
                    $i += 2;
                } else
                    $ret .= $str[$i];
        }
        return $ret;
    }

    //计算最大满数
    public function jstj($chzk_reach,$ysje){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje);
            }
        }
    }
    //计算最大满数--按照发运单位
    /**
     * @param $chzk_reach
     * @param $ysje
     * @param $xgj
     * @return bool|mixed
     */
    public function jstj2($chzk_reach,$ysje,$xgj){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max*$xgj){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje,$xgj);
            }
        }
    }

    /**
     * 出库申请单
     * @return float|int|string
     */
    public function produce_cksqd_SN(){
        //生成编号
        $max = db('cg_cksqd')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //提交工作流
    public function tjgzl(){
        $id = $this->request->param('id');

        //生成出库申请单,出库申请单明细
        $order = db('cg_order')->where(['id'=>$id])->find();

       /* $ins = [];
        $ins['sn'] = $this->produce_cksqd_SN();
        $ins['sqr'] = session('employee_id');
        $ins['sqrmc'] = db('employee')->where('id',$ins['sqr'])->value('em_name');
        $ins['sqrbm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where(['t2.employee_id'=>$ins['sqr']])->value('t.de_name');
        $ins['sqrq'] = date('Y-m-d');
        $ins['ckfs'] = '销售订单';
        $ins['dyck'] = null; //待定
        $ins['wllx'] = null; //待定
        $ins['sfxyfh'] = 1;
        $ins['shdz'] = $order['shdz'];
        $ins['shlxr'] = $order['shr'];
        $ins['shdh'] = $order['dh'];
        $ins['ckdxlx'] = $order['cusType'];
        $ins['ckdx'] = $order['cusName'];
        $ins['ckdx_name'] = $order['khmc'];
        $ins['order_sn'] = $order['sn'];
        $ins['order_id'] = $id;
        $bool = db('cg_cksqd')->insertGetId($ins);
        $ins2 = [];
        $mx = db('cg_order_list')->where('order_id',$id)->select();
        $i = 1;
        foreach($mx as $k=>$v){
            $t = [];
            $t['cksqd_id'] = $bool;
            $t['lx'] = $v['kind']==1?3:1;
            $t['sn'] = $i;
            $t['title'] = $v['product'];
            $t['title_name'] = $v['prod_name'];
            $t['pro_no'] = $v['prod_sn'];
            $t['unit'] = $v['unit'];
            $t['sqsl'] = $v['num']?$v['num']:$v['dzsl'];
            $t['tj'] = $v['tj'];
            $t['zl'] = $v['zl'];
            $t['dj'] = $v['xgj'];
            $t['num'] = $v['num']?$v['num']:$v['dzsl'];
            $t['zje'] = $v['ysje'];
            $t['bz'] = $v['beizhu'];
            $i++;
            $ins2[] = $t;
        }
        db('cg_cksqd_list')->insertAll($ins2);
        */
        $od=db("cg_order_list")->where(["order_id"=>$id])->count();
        if(!$od){
            echo json_encode(['success'=>false,'msg'=>'至少一条明细']);die;
        }
        $ret=$this->gowork(23,$id);
        $ret=json_decode($ret,true);

        
        if($ret["state"]==1){
            echo json_encode(['success'=>true,'msg'=>'提交成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'提交失败']);
        }
    }
    public function shenhe($myId,$trackId,$workId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
        $id = $aid;
        $data =  db('cg_order')->where('id',$id)->find();
        if($data["status"]==2){
            $this->redirect('Wdxsdd/update', ['id' => $aid,"from"=>2]);
            return;
        }
        $data['list'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>['in',[1,2]]])->select();
        $data['sqr'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['sqrbm'] = db('job t')->join('job_employee t2','t.id=t2.job_id')->where('t2.employee_id',$data['sqr'])->value('job_name');
        $data['sqrq'] = date('Y-m-d',$data['sqrq']);
        $data['cksqd_id'] = db('cg_cksqd')->where('order_id',$id)->value('id');
        $data['cksqd_sn'] = db('cg_cksqd')->where('order_id',$id)->value('sn');
        if($data['cusType']==1){
            $data['cusName'] = db('cg_jxs')->where('id',$data['cusName'])->value('title');
            $data['cusSN'] = db('cg_jxs')->where('id',$data['cusName'])->value('sn');
        }else{
            $data['cusName'] = db('cg_net')->where('id',$data['cusName'])->value('title');
            $data['cusSN'] = db('cg_net')->where('id',$data['cusName'])->value('sn');
        }
        foreach($data['list'] as $k=>$v){
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['mxbh'] = $data['sn'].'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            $v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            /*$zj1 += $v['num'];
            $zj2 += $v['dzsl'];
            $zj3 += $v['yje'];
            $zj4 += $v['ysje'];*/
            if($v['dyddmxid'])
                $v['dyddmxid'] = $data['sn'].'-'.db('cg_order_list')->where('id',$v['dyddmxid'])->value('sn');

            $data['list'][$k]= $v;
        }
        $data['huobu'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>3])->select();
        foreach($data['huobu'] as $k=>$v){
            $v['pro_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            $v['prod_sn'] = db('pro_products')->where('id',$v['product'])->value('pro_no');
            $main_sn = db('cg_ti_hexiao_list t')->join('cg_ti_hexiao t2','t2.id=t.hx_id')->where('t.id',$v['hxdmxbh'])->value('t2.sn');
            $sub_sn = db('cg_ti_hexiao_list')->where('id',$v['hxdmxbh'])->value('sn');
            $v['hxdbh'] = $main_sn.'_'.$sub_sn;
            $v['mxbh'] = db('cg_order')->where('id',$v['order_id'])->value('sn').'-'.$v['sn'];
            $v['category'] = db('pro_category t')->join('pro_series t2','t.id=t2.category_id')->join('pro_sku t3','t3.series_id=t2.id')->join('pro_products t4','t4.sku_id=t3.id')->where('t4.id',$v['product'])->value('t.category_name');
            $v['order_sn'] = db('cg_order')->where('id',$v['order_id'])->value('sn');
            $v['format'] = db('pro_products')->where('id',$v['product'])->value('format');
            $v['pro_sku'] = db('pro_products')->where('id',$v['product'])->value('pro_sku');
            //$v['unit'] = db('pro_products')->where('id',$v['product'])->value('unit');
            $v['box_volume'] = db('pro_products')->where('id',$v['product'])->value('box_volume');
            $v['weight'] = db('pro_products')->where('id',$v['product'])->value('weight');
            $data['huobu'][$k] = $v;
        }
        $data['bufei'] = db('cg_order_list')->where(['order_id'=>$id,'xslx'=>4])->select();
        $this->assign('data',$data);
         $logs=$this->getlog(23,$aid);
            //print_r($logs);
            $this->assign("logs",$logs);
        return $this->fetch();
    }
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
        $fid=23;$aid=$data["id"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            $up["id"]=$aid;
            $up["status"]=8;
            try{
                db("cg_order")->update($up);
                //补费补货处理
            }catch (\Exception $e){
        
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
            
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    public function baocunchuli(){
        $request = Request::instance();
        $data = $request->post();

        $valid = new Valid([
                'cusType|客户类型'=>'require',
                'cusName|客户名称'=>'require',
                'shdz|收货地址'=>'require',
                'shr|收货人'=>'require',
                'dh|收货电话'=>'require',
                'jyfhrq|建议发货日期'=>'require|dateFormat:Y-m-d',
                'zysx|注意事项'=>'require',
            ]);
            if(false==$valid->check($data)){
                echo json_encode(["state" => 2,'msg'=>$valid->getError()]);die;
            }
            $od=db("cg_order_list")->where(["order_id"=>$data["id"]])->count();
            if(!$od){
                echo json_encode(["state" => 2,'msg'=>"至少添加一条明细"]);die;
            }
            if($data['cusType']==1){
                $data['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t.id=t2.zoning')->where('t2.id',$data['cusName'])->value('t.title');
                $data['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t.id=t2.provice')->where('t2.id',$data['cusName'])->value('t.title');
                $data['city'] = db('cg_market_city t')->join('cg_jxs t2','t.id=t2.city')->where('t2.id',$data['cusName'])->value('t.title');
                $data['khbh'] = db('cg_jxs')->where('id',$data['cusName'])->value('sn');
                $data['khmc'] = db('cg_jxs')->where('id',$data['cusName'])->value('title');
            }else{
                $data['zoning'] = db('cg_market_zoning t')->join('cg_net t2','t.id=t2.zoning')->where('t2.id',$data['cusName'])->value('t.title');
                $data['provice'] = db('cg_market_provice t')->join('cg_net t2','t.id=t2.provice')->where('t2.id',$data['cusName'])->value('t.title');
                $data['city'] = db('cg_market_city t')->join('cg_net t2','t.id=t2.city')->where('t2.id',$data['cusName'])->value('t.title');
                $data['khbh'] = db('cg_net')->where('id',$data['cusName'])->value('sn');
                $data['khmc'] = db('cg_net')->where('id',$data['cusName'])->value('title');
            }
            $data['yhPolicymc'] = db('cg_channel_preferential_policy')->where('id',$data['yhPolicy'])->value('title');
//            $data['jyfhrq'] = strtotime($data['jyfhrq']);
            $data['ptime'] = time();
            $data["status"]=3;
            $data['puser'] = session('employee_id');
            unset($data['attach']);
            unset($data['remove']);
            $nodeKey=$data["nodeKey"];
            unset($data["nodeKey"]);
            $selectId=$data["selectId"];
            unset($data["selectId"]);
            $selectName=$data["selectName"];
            unset($data["selectName"]);
            $bool = db('cg_order')->update($data);
         if ($bool) {
                $fid=23;$aid=$data["id"];
                $res=$this->goworker($fid,$aid,$nodeKey,$selectId,$selectName);
                            if($res["operateStatus"]=="success"){
                                
                                return json_encode(["msg"=>"","state"=>1]);
                            }else{
                                
                                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                            }
            } else {
                
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

    }
}